# -*- coding: utf-8 -*-
"""
Created on Thu Oct 24 16:55:57 2013

@author: meka
"""
import matplotlib.pyplot as plt
import glob
import os
import numpy as np
import scipy.stats as stats

def readGSRdata(filename):
    gsr = []
    myfile = open(filename, "r");
    myfile.readline()
    for line in myfile:
        val = float(line.split("\t")[-1])
        if val < 0.1 or val > 20:
            continue;
        gsr.append(val);
        
    return gsr;
 
def readHRdata(filename):
    lhr = []
    rhr = []
    myfile = open(filename, "r");
    myfile.readline()
    for line in myfile:
        lval = int(line.split("\t")[-2])
        rval = int(line.split("\t")[-1])
        if abs(lval - rval) > 10:
            #print "before: ",lval, rval
            lval = max(lval, rval)
            rval = max(lval, rval)
        #print "after:", lval, rval
        if lval > 50 and lval < 120:
            lhr.append(lval);
        if rval > 50 and rval < 120:
            rhr.append(rval)
        
    if len(lhr) == 0: lhr.append(0)
    if len(rhr) == 0: rhr.append(0)
        
    return lhr, rhr;
    
def readGSRDataFromFolder(folder):
    filenames = sorted(glob.glob(folder + '/GSR*.txt'))
    basegsr = []
    easygsr = []
    hardgsr = []
    for filename in filenames:
        if "Baseline" in filename:
            basegsr.extend(readGSRdata(filename)[:]);
        if "easy" in filename:
            easygsr.extend(readGSRdata(filename)[:]);
        if "hard" in filename:
            hardgsr.extend(readGSRdata(filename)[:])
            
    
    
    return (basegsr - np.mean(basegsr))/np.std(basegsr), (easygsr - np.mean(easygsr))/np.std(easygsr), (hardgsr - np.mean(hardgsr))/np.std(hardgsr);
    
def displayGSRData(fold):
    basemean = []
    easymean = []
    hardmean = []
    basestd = []    
    easystd = []    
    hardstd = []   
    for folder in getFolderfromFolder(fold):
        basegsr, easygsr, hardgsr = readGSRDataFromFolder(folder);
        basemean.append(np.mean(basegsr))
        easymean.append(np.mean(easygsr))
        hardmean.append(np.mean(hardgsr))
        
        basestd.append(np.std(basegsr))
        easystd.append(np.std(easygsr))
        hardstd.append(np.std(hardgsr))
        #print basegsr, easygsr, hardgsr
    plt.figure();
        
    plt.plot(basemean,  'r-', basestd, 'rs')
    plt.plot(easymean,  'g-', easystd, 'gs')
    plt.plot(hardmean,  'b-', hardstd, 'bs')
    plt.title(folder)
    print folder, (np.mean(basemean), np.std(basemean)), (np.mean(easymean), np.std(easymean)),(np.mean(hardmean), np.std(hardmean))
    
    
def readHRDataFromFolder(folder):
    filenames = sorted(glob.glob(folder + '/ECG*.txt'))
    baselhr = []
    easylhr = []
    hardlhr = []
    baserhr = []
    easyrhr = []
    hardrhr = []
    for filename in filenames:
        if "Baseline" in filename:
            l, r = readHRdata(filename)
            baselhr.extend(l);
            baserhr.extend(r)
        if "easy" in filename:
            l, r = readHRdata(filename)
            easylhr.extend(l);
            easyrhr.extend(r)        
        if "hard" in filename:
            l, r = readHRdata(filename)
            hardlhr.extend(l);
            hardrhr.extend(r)
            
    return baselhr, baserhr, easylhr, easyrhr, hardlhr, hardrhr;
    
def displayHRData(fold):
    mean = []
    stddev = []
    
    for folder in getFolderfromFolder(fold):

        baselhr, baserhr, easylhr, easyrhr, hardlhr, hardrhr = readHRDataFromFolder(folder);
        mean.extend([np.mean(baselhr),np.mean(baserhr), np.mean(easylhr),np.mean(easyrhr), np.mean(hardlhr),np.mean(hardrhr)])
        stddev.extend([np.std(baselhr),np.std(baserhr), np.std(easylhr),np.std(easyrhr), np.std(hardlhr),np.std(hardrhr)])
#        plt.figure();
#        
#        plt.plot(baselhr,  'r-', baserhr, 'r+')
#        plt.plot(easylhr,  'g-', easyrhr, 'g+')
#        plt.plot(hardlhr,  'b-', hardrhr, 'b+')
#        plt.title(folder)
    
    meanbaselhr = [mean[x] for x in range(len(mean)) if x % 6 ==0]
    meanbaserhr = [mean[x] for x in range(len(mean)) if x % 6 ==1]
    meaneasylhr = [mean[x] for x in range(len(mean)) if x % 6 ==2]
    meaneasyrhr = [mean[x] for x in range(len(mean)) if x % 6 ==3]
    meanhardlhr = [mean[x] for x in range(len(mean)) if x % 6 ==4]
    meanhardrhr = [mean[x] for x in range(len(mean)) if x % 6 ==5]
    
    stddevbaselhr = [stddev[x] for x in range(len(stddev)) if x % 6 ==0]
    stddevbaserhr = [stddev[x] for x in range(len(stddev)) if x % 6 ==1]
    stddeveasylhr = [stddev[x] for x in range(len(stddev)) if x % 6 ==2]
    stddeveasyrhr = [stddev[x] for x in range(len(stddev)) if x % 6 ==3]
    stddevhardlhr = [stddev[x] for x in range(len(stddev)) if x % 6 ==4]
    stddevhardrhr = [stddev[x] for x in range(len(stddev)) if x % 6 ==5]
#    meanbaselhr.append(np.mean(meanbaselhr))
#    meanbaserhr.append(np.mean(meanbaserhr))
#    meaneasylhr.append(np.mean(meaneasylhr))
#    meaneasyrhr.append(np.mean(meaneasyrhr))
#    meanhardlhr.append(np.mean(meanhardlhr))
#    meanhardrhr.append(np.mean(meanhardrhr))
    
    #print stats.f_oneway(meanbaselhr, meanbaserhr)
    print fold, np.mean(meanbaselhr),np.std(meanbaselhr),np.mean(meanhardlhr),np.std(meanhardlhr), np.mean(meaneasylhr),np.std(meaneasylhr)
    plt.figure();
        
    ind = np.arange(len(meanbaselhr))
    width = 0.25
    plt.bar(ind, meanbaselhr, width,color= 'r', yerr=stddevbaselhr, label='baseline')#, meanbaserhr, 'rs')
    plt.bar(ind + width, meanhardlhr, width, color=  'g', yerr=stddevhardlhr, label='easy level')#, meanhardrhr, 'bs')
    plt.bar(ind + 2*width, meaneasylhr, width, color= 'b', yerr=stddeveasylhr, label='difficult level')#, meaneasyrhr, 'gs')
    plt.xlabel('participant')
    plt.ylabel('Average heart rate (BPM)')
    plt.legend()
    plt.title('Participants\' heart rate in quadromotor driving condition')
    #print fold, (np.mean(basemean), np.std(basemean)), (np.mean(easymean), np.std(easymean)),(np.mean(hardmean), np.std(hardmean))
    

def getFolderfromFolder(folder):
    folders = []
    for dirname, dirnames, filenames in os.walk(folder):
        # print path to all subdirectories first.
        for subdirname in dirnames:
            folders.append( os.path.join(dirname, subdirname))
            
    return folders
    
def compareGSRDroneNySYS(dronefolder, nysysfolder):
    fold = nysysfolder;
    basemean = []
    easymean = []
    hardmean = []
    basestd = []    
    easystd = []    
    hardstd = []    
    for folder in getFolderfromFolder(fold):
        basegsr, easygsr, hardgsr = readGSRDataFromFolder(folder);
        basemean.append(np.mean(basegsr))
        easymean.append(np.mean(easygsr))
        hardmean.append(np.mean(hardgsr))
        
        basestd.append(np.std(basegsr))
        easystd.append(np.std(easygsr))
        hardstd.append(np.std(hardgsr))
        
#    basestd=[np.std(basemean)]
#    easystd=[np.std(easymean)]
#    hardstd=[np.std(hardmean)]        
#    basemean=[np.mean(basemean)]
#    easymean=[np.mean(easymean)]
#    hardmean=[np.mean(hardmean)]
        #print basegsr, easygsr, hardgsr
    plt.figure();
        
    ind = np.arange(len(basemean))
    width = 0.25
    plt.bar(ind, basemean, width,  color='r', label='baseline')#, np.add(basemean,basestd), 'r--', np.subtract(basemean,basestd), 'r--')
    plt.bar(ind+width, easymean, width, color=  'g',label='easy level')#, np.add(hardmean,hardstd), 'b--', np.subtract(hardmean,hardstd), 'b--')
    plt.bar(ind + 2*width, hardmean, width,  color='b', label='difficult level')#, np.add(easymean,easystd), 'g--', np.subtract(easymean,easystd), 'g--')
    plt.title('Participants\' GSR in simulated driving condition')
    plt.xlabel("Participant")
    plt.ylabel("Average skin conductance (MicroSiemens)")
    plt.legend()
    print fold, (np.mean(basemean), np.std(basemean)), (np.mean(easymean), np.std(easymean)),(np.mean(hardmean), np.std(hardmean))
#    
    fold = dronefolder;
    basemean = []
    easymean = []
    hardmean = []
    basestd = []    
    easystd = []    
    hardstd = []    
    for folder in getFolderfromFolder(fold):
        basegsr, easygsr, hardgsr = readGSRDataFromFolder(folder);
        basemean.append(np.mean(basegsr))
        easymean.append(np.mean(easygsr))
        hardmean.append(np.mean(hardgsr))
        
        basestd.append(np.std(basegsr))
        easystd.append(np.std(easygsr))
        hardstd.append(np.std(hardgsr))
        #print basegsr, easygsr, hardgsr
    
#    basestd=[np.std(basemean)]
#    easystd=[np.std(easymean)]
#    hardstd=[np.std(hardmean)]        
#    basemean=[np.mean(basemean)]
#    easymean=[np.mean(easymean)]
#    hardmean=[np.mean(hardmean)]
    
    plt.figure();
        
    ind = np.arange(len(basemean))
    width = 0.25
    plt.bar(ind, basemean, width,  color='r',  label='baseline')#, np.add(basemean,basestd), 'r--', np.subtract(basemean,basestd), 'r--')
    plt.bar(ind+width, hardmean, width, color=  'g', label='easy level')#, np.add(hardmean,hardstd), 'b--', np.subtract(hardmean,hardstd), 'b--')
    plt.bar(ind + 2*width, easymean, width,  color='b', label='difficult level')#, np.add(easymean,easystd), 'g--', np.subtract(easymean,easystd), 'g--')
    plt.title('Participants\' GSR in quadromoto driving condition')
    plt.xlabel("Participant")
    plt.ylabel("Average skin conductance (MicroSiemens)")
    #plt.bar([0, 1, 2], [0.2, 0.3, 0.1], width=0.4, label="Bar 1", align="center")
    plt.legend()
    print fold, (np.mean(basemean), np.std(basemean)), (np.mean(easymean), np.std(easymean)),(np.mean(hardmean), np.std(hardmean))
        
if __name__ == '__main__':
    dronefold = "../dataDrone_inCharacteristics";
    nySYSFold = "../dataNySYS"
    compareGSRDroneNySYS(dronefold, nySYSFold)
    
    #displayHRData(nySYSFold)

    
    